<?php
/**
 * Created by PhpStorm.
 * User: longli
 * Date: 2020/09/10
 * Time: 19:25
 * @link http://www.lmterp.cn
 */

namespace app\common\model;

use PDOStatement;
use think\Collection;

class Warehouse extends BaseModel
{
    protected $pk = 'warehouse_id';

    protected $autoWriteTimestamp = 'datetime';

    protected $insert = ['create_by', 'update_by'];

    protected $update = ['update_by'];

    /**
     * 启用
     */
    const STATUS_Y = 1;

    /**
     * 关闭
     */
    const STATUS_N = 0;

    public static $STATUS = [
        self::STATUS_Y => '启用',
        self::STATUS_N => '关闭'
    ];

    protected function setCreateByAttr()
    {
        if($this->isCli) return 0;
        $admin = session('lmterp');
        return $admin ? $admin->id : 0;
    }

    protected function setUpdateByAttr()
    {
        if($this->isCli) return 0;
        $admin = session('lmterp');
        return $admin ? $admin->id : 0;
    }

    /**
     * 仓库名称是否存在
     * @param string $name 分类名
     * @return bool
     * @date 2020/09/11
     * @author longli
     */
    public static function hasByName($name)
    {
        return !!static::where(['name' => $name])->count();
    }

    /**
     * 仓库代码是否存在
     * @param string $code 分类名
     * @return bool
     * @date 2020/09/14
     * @author longli
     */
    public static function hasByCode($code)
    {
        return !!static::where(['code' => $code])->count();
    }

    /**
     * 通过名称获取仓库
     * @param string $name 分类名
     * @return bool
     * @date 2020/09/11
     * @author longli
     */
    public static function getByName($name)
    {
        return static::where(['name' => $name])->find();
    }

    /**
     * 获取所有仓库
     * @return array|PDOStatement|string|Collection
     * @date 2020/09/12
     * @author longli
     */
    public static function getAll()
    {
        return static::where(['status' => self::STATUS_Y])->select();
    }

    /**
     * 仓库信息
     * @param int|int[] $ids 仓库 id
     * @param array $data 分类信息
     * @return bool
     * @date 2020/09/14
     * @author longli
     */
    public static function editByWarehouseId($ids, $data)
    {
        try
        {
            foreach(static::where("warehouse_id", "in", $ids)->select() as $warehouse)
            {
                $warehouse->save($data);
            }
            return true;
        }catch(\Exception $e)
        {
            return false;
        }
    }
}
